package com.sunlg.smarthome.contract.presenter;

import com.sunlg.smarthome.base.App;
import com.sunlg.smarthome.base.C;
import com.sunlg.smarthome.contract.AddEnvirDeviceContract;
import com.sunlg.smarthome.data.entity.EnvirDevice;
import com.sunlg.smarthome.data.remote.MySubscriber;
import com.sunlg.smarthome.data.remote.Result;
import com.sunlg.smarthome.data.remote.SHServiceWrapper;
import com.sunlg.smarthome.utils.PreferHelper;

/**
 * Created by sunlg on 2017/5/12.
 */

public class AddEnvrDevicePresenter implements AddEnvirDeviceContract.Presenter {

    private PreferHelper preferHelper;
    private SHServiceWrapper mSHServiceWrapper;
    private AddEnvirDeviceContract.View mView;

    public AddEnvrDevicePresenter() {
        preferHelper = new PreferHelper(App.getInstance(), "gateway");
        mSHServiceWrapper = App.getInstance().getServiceWrapper();
    }

    @Override
    public void addEnvirDevice(EnvirDevice envirDevice) {
        envirDevice.setGatewayId(preferHelper.getInt("id", 0));
        mSHServiceWrapper.addEnvirDevice(envirDevice, new MySubscriber<Result>() {
            @Override
            public void onSuccess(Result data) {
                if(data.getCode() == C.ActionStatus.SUCCESS){
                    mView.addSuccess();
                }else {
                    _onError(new Throwable(data.getMsg()));
                }
            }

            @Override
            public void _onError(Throwable e) {
                mView.showError(e.getMessage());
            }
        });
    }

    @Override
    public void attachView(AddEnvirDeviceContract.View view) {
        this.mView = view;
    }

    @Override
    public void dettachView() {
        this.mView = null;
    }
}
